package presentation;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hibernate.Session;

import db.DbUtils;
import db.Picture;

public class NextPageServlet extends javax.servlet.http.HttpServlet implements
		javax.servlet.Servlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		Long imageId = Long.parseLong(request.getParameter("image"));
		int page = Integer.parseInt(request.getParameter("page"));
		long allPicNum=(Long)session.getAttribute("allPicNum");
		Session hbSession = DbUtils.startSession();
		List<Picture> pictures = DbUtils.get16Pictures(hbSession, page);
		int index = 0;
		for (int i = 0; i < pictures.size(); i++) {
			if (pictures.get(i).getPictureId() == imageId) {
				index = i;
			}
		} 
			if ((index == pictures.size()-1) && (page < allPicNum)) {
			page++;
			session.setAttribute("pageNum", page);
			pictures = DbUtils.get16Pictures(hbSession, page);
			index = 0;
			response.sendRedirect("ViewPicture.jsp?image=" + pictures.get(index).getPictureId());
		}else if ((index == pictures.size()-1) && (page == allPicNum)){
			response.sendRedirect("ViewPicture.jsp?image=" + pictures.get(index).getPictureId());
		} else {
			response.sendRedirect("ViewPicture.jsp?image=" + pictures.get(++index).getPictureId());
		}	
	}
}